<template>
  <div
    v-if="editCanvas.isSelect"
    class="edit-select"
    :style="positionStyle"
  >
    <div class="select-background" />
    <div class="select-border" />
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { selectBoxIndex } from '@/settings'
import styleMixin from '../../mixins/style'
export default {
  mixins: [styleMixin],
  computed: {
    ...mapGetters(['editCanvas', 'mousePosition']),
    scale () {
      return this.editCanvas.scale
    }
  },
  data () {
    return {
      positionStyle: {}
    }
  },
  watch: {
    mousePosition: {
      handler (positionInfo) {
        if (!this.editCanvas.isSelect) return
        // 这里的 x,y 是已经计算过的相对位移值
        const { startX, startY, x, y } = positionInfo

        const attr = {
          zIndex: selectBoxIndex,
          // left
          x: 0,
          // top
          y: 0,
          // 宽
          w: 0,
          // 高
          h: 0,
          // 偏移
          offsetX: 0,
          offsetY: 0
        }

        // 处理位置
        if (x > startX && y > startY) {
          // 右下方向
          attr.x = startX
          attr.y = startY
          attr.w = Math.round((x - startX) / this.scale)
          attr.h = Math.round((y - startY) / this.scale)
        } else if (x > startX && y < startY) {
          // 右上方向
          attr.x = startX
          attr.w = Math.round((x - startX) / this.scale)
          attr.h = Math.round((startY - y) / this.scale)
          attr.y = startY - attr.h
        } else if (x < startX && y > startY) {
          // 左下方向
          attr.y = startY
          attr.w = Math.round((startX - x) / this.scale)
          attr.h = Math.round((y - startY) / this.scale)
          attr.x = startX - attr.w
        } else {
          // 左上方向
          attr.w = Math.round((startX - x) / this.scale)
          attr.h = Math.round((startY - y) / this.scale)
          attr.x = startX - attr.w
          attr.y = startY - attr.h
        }

        this.positionStyle = {
          ...this.useComponentStyle(attr, selectBoxIndex),
          ...this.useSizeStyle(attr)
        }
      },
      deep: true
    }
  }
}
</script>

<style lang="scss" scoped>
.edit-select {
  position: absolute;
  .select-border,
  .select-background {
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    overflow: hidden;
  }
  .select-border {
    left: 0;
    top: 0;
    opacity: 0.5;
    border-width: 2px;
    border-style: solid;
    border-color: #51d6a9;
  }
  .select-background {
    top: 2px;
    left: 2px;
    opacity: 0.2;
    background-color: #51d6a9;
  }
}
</style>